package com.bozer.springsecuritydemo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bozer.springsecuritydemo.dao.RoleDao;
import com.bozer.springsecuritydemo.dao.UserDao;
import com.bozer.springsecuritydemo.dao.UserRoleDao;
import com.bozer.springsecuritydemo.entity.Role;
import com.bozer.springsecuritydemo.entity.User;
import com.bozer.springsecuritydemo.entity.UserRole;
import com.bozer.springsecuritydemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author bozer
 * @since 2020-08-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return this.lambdaQuery().eq(User::getUsername, username).oneOpt().map(user -> {
            List<Integer> roleIds = userRoleDao.selectList(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, user.getId())).stream().map(UserRole::getRoleId).collect(Collectors.toList());
            List<SimpleGrantedAuthority> collect = roleDao.selectList(Wrappers.<Role>lambdaQuery().in(Role::getId, roleIds)).stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
            return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),user.getEnable(),user.getAccountNonExpired(),user.getCredentialsNonExpired(),user.getAccountNonLocked(),collect);
        }).orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
    }
}
